#! /bin/bash

bname=`basename $0`
usage="$bname --help \t\t\t\t\t\t\t\t - shows this\n$bname repeat_count sim_time {m|t} [input_files] [\"+\"versions]  \t\t - run the 'input_files' test inputs (delimitered with space) for 'repeat_count' times, each for 'sim_time' ms, m/t for methods or threads, for specified versions, as follows:\n\tversion - one of systemc versions or \"all\"\n\nFor example:\n\t$bname 5 10 m ./input/timed_only/* +all"

if [ ! -n "$*" ]
then
	echo  -e $usage
	exit
fi

case $1 in '-h'|'-help'|'--help')
	echo  -e $usage
	exit;;
esac


repeat_count=$1
sim_time=$2
is_thread=$3
shift 3

name='event'

red='\E[31;47m'
green='\E[32;47m'
yellow='\E[33;30m'
cyan='\E[36;47m'

cecho(){
	echo -e "$1""$2"
	tput sgr0
}

fail=" \E[31;47mFAIL"
pass=" \E[32;47mPASS"
report_prefix(){
	echo -n '[ '$1' | '$2' ]'	
}
versions=`echo $* | grep -o "\+[[:graph:]]*[[:space:]]*" | sed "s|\+||" | xargs`
input_files=`echo $* | sed "s|[-+][[:graph:]]*[[:space:]]*||g"`
#sim_params=`echo $* | grep -o "\-[[:graph:]]*[[:space:]]*" | xargs`
sim_params="$sim_time $is_thread 0"
verbose=1

echo "repeat_count is $repeat_count"
echo "sim_time is $sim_time"
echo "is_thread is $is_thread"

test_root=$SYSCPAR_ROOT/tests/$name
precompiled=$spawn_root/precompiled_test.cpp
precompiled_inj=$spawn_root/precompiled_test_inj.cpp


go(){
	:> wrapper
	if [[ -d $SYSCPAR_ROOT/code/$1 ]]; then
		test_executable=$test_root/"$name"_$1

		#precompile
		make precompile_$1

		for x in $input_files
		do
			#inject & compile
			echo -e '#include "'$x'"'"\n" > $test_root/wrapper			# inject the #include directive
			make compile_$1 build_$1

			#run test
			fast_test $1 $x	
		done
		rm -f $test_executable
	else
	 	cecho "Version '$1' not found"
	fi
}

run(){
	for ((i=1; i <= repeat_count ; i++))
	do
		$test_executable $sim_params | grep 'is running ok' | wc -l
		echo -n '.' >&2
	done
}

fast_test(){
	#$1 is version
	#$2 is test filename

	report_prefix $1 $2
	num_lines=`run | uniq -c | tee 'tmp~' | wc -l`
	if (( num_lines == 0 )); then cecho "$red" "smth went really wrong, exiting"; exit 1; fi
	if (( num_lines > 1 ));	then cecho $fail ; else cecho $pass; fi
	[[ "$verbose" ]] && cat 'tmp~'
	rm -f 'tmp~'
}

[[ "$versions" == "all" ]] && { pushd $SYSCPAR_ROOT/code; versions=`echo *`; popd; }

for v in $versions; do go $v; done
make clean



